package learn_202005;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

public class TomcatServer {
    static ByteBuffer byteBuffer = ByteBuffer.allocate(512);
    static List<SocketChannel> channelList = new ArrayList<>();
    public static void main(String[] args) {
        try {
            ServerSocketChannel serverSocket = ServerSocketChannel.open();
            SocketAddress socketAddress = new InetSocketAddress("127.0.0.1",9999);
            serverSocket.bind(socketAddress);
            serverSocket.configureBlocking(false); // 设定serverSocket.accept()不阻塞
            while (true){
//                Thread.sleep(2000);
                // 请求内容读取（第一次进入不执行）
                for (SocketChannel socketChannel: channelList){
                    // 尝试从请求中取得数据
                    int read = socketChannel.read(byteBuffer);
                    if(read > 0){
                        System.out.println("read(" + read + "):");
                        byteBuffer.flip();
                        byte[] bs = new byte[read];
                        byteBuffer.get(bs);
                        String content = new String(bs);
                        System.out.print(content);
                        System.out.println();
                        byteBuffer.flip();
                    }
                }
                // 接受请求
                SocketChannel accept = serverSocket.accept();
                if (accept != null){
                    System.out.println("连接成功");
                    accept.configureBlocking(false); // 设定socketChannel.read(byteBuffer)不阻塞
                    channelList.add(accept);
                    System.out.println("list:" + channelList.size());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
